package com.runshu.newsmartark.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.runshu.newsmartark.base.MyApplication;
import com.runshu.newsmartark.common.ConstantUrl;
import com.runshu.newsmartark.dbutil.RefreshUtils;
import com.runshu.newsmartark.entity.UserInfoEntity;
import com.runshu.newsmartark.event.Event;
import com.runshu.newsmartark.event.EventBusUtils;
import com.runshu.newsmartark.event.EventCode;
import com.runshu.newsmartark.reader.base.CMD;
import com.runshu.newsmartark.reader.base.ReaderBase;
import com.runshu.newsmartark.reader.helper.InventoryBuffer;
import com.runshu.newsmartark.reader.helper.ReaderHelper;
import com.runshu.newsmartark.reader.helper.ReaderSetting;
import com.runshu.newsmartark.util.HexDump;
import com.runshu.newsmartark.util.StringUtils;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.SharedPreferencesUtils;
import com.runshu.newsmartark.util.y.nativelog.NLogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * 柜子自检，记录远程日志
 */
public class SelfCheckService extends Service {
    int refreshAllDataTime = 15 * 60 * 1000;

    SyncDataTask task;
    public static ReaderSetting m_curReaderSetting;
    public ReaderHelper mReaderHelper;
    public ReaderBase mReader;
    protected static InventoryBuffer m_curInventoryBuffer;

    @Override
    public void onCreate() {
        super.onCreate();
        initBox();
        task = new SyncDataTask();
        task.start();
        initReceiver();
    }

    private void initBox() {
        try {
            mReaderHelper = ReaderHelper.getDefaultHelper();
            mReader = mReaderHelper.getReader();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        m_curInventoryBuffer = mReaderHelper.getCurInventoryBuffer();
        m_curReaderSetting = mReaderHelper.getCurReaderSetting();
    }

    //柜子操作相关接收
    private LocalBroadcastManager lbm;

    private void initReceiver() {
        lbm = LocalBroadcastManager.getInstance( this );
        IntentFilter itent = new IntentFilter();
        itent.addAction( ReaderHelper.BROADCAST_WRITE_LOG );
        itent.addAction( ReaderHelper.BROADCAST_REFRESH_INVENTORY_REAL );
        itent.addAction( ReaderHelper.BROADCAST_REFRESH_INVENTORY );
        itent.addAction( ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH_TERMINAL );
        itent.addAction( ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH );
        itent.addAction( ReaderHelper.BROADCAST_WRITE_LOG );
        itent.addAction( ReaderHelper.BROADCAST_REFRESH_READER_SETTING );
        lbm.registerReceiver( mRecv, itent );
    }

    // add by lei.li 2016/11/14
    private final BroadcastReceiver mRecv = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals( ReaderHelper.BROADCAST_REFRESH_READER_SETTING )) {
                byte btCmd = intent.getByteExtra( "cmd", (byte) 0x00 );

                if (btCmd == CMD.READ_GPIO_VALUE || btCmd == CMD.WRITE_GPIO_VALUE) {
                    try {
                        UserInfoEntity userInfoGlob = MyApplication.getUserInfoGlob();
                        LogUtil.e("Gpio1Value", (String.valueOf(m_curReaderSetting.btGpio1Value)));
                        LogUtil.e("Gpio2Value", (String.valueOf(m_curReaderSetting.btGpio2Value)));
                        LogUtil.e("Gpio3Value", (String.valueOf(m_curReaderSetting.btGpio3Value)));

                        if (m_curReaderSetting.btGpio1Value == 0x00) {
                            //门关了
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put( "operate", "closeDoor" );
                            jsonObject.put( "user", userInfoGlob == null ?
                                    "none/manual" : "<id>" + userInfoGlob.getId() +
                                    "<name>" + userInfoGlob.getUsername() +
                                    "<usrCode>" + userInfoGlob.getUsercode() +
                                    (openTime == 0 ? "" :
                                            "本次开门最低时长" + ((System.currentTimeMillis() - openTime) / 1000 / 60) + "分钟") );
                            NLogUtil.i( NLogUtil.INFO_OPERATE_Box, jsonObject.toString() );
                            openTime = 0;
                        } else {
                            //门开了
                            openTime = System.currentTimeMillis();
//                            showToast( "service 开门了" );
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put( "operate", "openDoor" );
                            jsonObject.put( "user", userInfoGlob == null ?
                                    "none/manual" : "<id>" + userInfoGlob.getId() +
                                    "<name>" + userInfoGlob.getUsername() +
                                    "<usrCode>" + userInfoGlob.getUsercode() );
                            NLogUtil.i( NLogUtil.INFO_OPERATE_Box, jsonObject.toString() );
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            } else if (intent.getAction().equals( ReaderHelper.BROADCAST_WRITE_LOG )) {


            }

            if (intent.getAction().equals( ReaderHelper.BROADCAST_REFRESH_INVENTORY_REAL )
                    || intent.getAction().equals( ReaderHelper.BROADCAST_REFRESH_INVENTORY )
                    || intent.getAction().equals( ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH )) {
                Log.d( "Real time receive", Thread.currentThread().getName() );
                byte btCmd = intent.getByteExtra( "cmd", (byte) 0x00 );
//                Log.d("action", bytesToHexString(btCmd));
                switch (btCmd) {
                    case CMD.REAL_TIME_INVENTORY:
                    case CMD.CUSTOMIZED_SESSION_TARGET_INVENTORY:
                        if (m_curInventoryBuffer.lsTagList.size() > 0) ;
                    {
                        Log.d( "TAGS", m_curInventoryBuffer.lsTagList.get( 0 ).strEPC );
                    }


//                    mHandler.removeCallbacks(mRefreshRunnable);
//                    mHandler.postDelayed(mRefreshRunnable, 2000);
//                    // add by lei.li 2016/11/14
//                    mLoopHandler.removeCallbacks(mLoopRunnable);
//                    mLoopHandler.postDelayed(mLoopRunnable, 2000);
                    //refreshText();
                    break;
                    case CMD.GET_INVENTORY_BUFFER:
                    case CMD.GET_AND_RESET_INVENTORY_BUFFER:
                        break;
                    case ReaderHelper.INVENTORY_ERR:
                    case ReaderHelper.INVENTORY_ERR_END:
                    case ReaderHelper.INVENTORY_END:
                        // add by lei.li have some problem why it was annotation
                        // refreshList();
                        // add by lei.li
                        // add by lei.li 2016/11/
                        if (mReaderHelper.getInventoryFlag() /* || bTmpInventoryFlag */) {
//                            mLoopHandler.removeCallbacks(mLoopRunnable);
//                            mLoopHandler.postDelayed(mLoopRunnable, 2000);

                        } else {
//                            mLoopHandler.removeCallbacks(mLoopRunnable);
//                            // add by lei.li 2016/11/14
//                            mHandler.removeCallbacks(mRefreshRunnable);
                            // add by lei.li 2016/11/14
                        }

                        // start_add by lei.li 2016/11/04
                        // refreshStartStop(false);
                        // end_add by lei.li 2016/11/04
                        // start_add by lei.li 2016/11/04
                        break;
                }

            } else if (intent.getAction().equals( ReaderHelper.BROADCAST_WRITE_LOG )) {
            } else if (intent.getAction().equals( ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH_TERMINAL )) {
//                showToast( "service 盘点了一次" );
                UserInfoEntity userInfoGlob = MyApplication.getUserInfoGlob();
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put( "operate", "scanGoods" );
                    jsonObject.put( "user", userInfoGlob == null ?
                            "none/manual" : "<id>" + userInfoGlob.getId() +
                            "<name>" + userInfoGlob.getUsername() +
                            "<usrCode>" + userInfoGlob.getUsercode() );
                    NLogUtil.i( NLogUtil.INFO_OPERATE_Box, jsonObject.toString() );
                    Log.d( "action", "停止" );
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage( msg );
            Toast.makeText( SelfCheckService.this, msg.getData().getString( "msg" ), Toast.LENGTH_SHORT ).show();

        }
    };

    private void showToast(String msg) {
        Message msg1 = new Message();
        Bundle data = new Bundle();
        data.putString( "msg", msg );
        msg1.setData( data );
        handler.sendMessage( msg1 );
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand( intent, flags, startId );
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        task.stop();
        task = null;
        if (lbm != null)
            lbm.unregisterReceiver( mRecv );
    }

    long openTime = 0;

    public class SyncDataTask extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
                while (true) {
                    sleep( 1000 * 60*15 );
                    //定时的自检 todo
                    byte btGpio1Value = m_curReaderSetting.btGpio1Value;
                    int isOpen = btGpio1Value & 0x01;
                    if (isOpen == 0x01) {
                        if (openTime == 0) {
                            openTime = System.currentTimeMillis();
                        } else {
                            long time = (System.currentTimeMillis() - openTime) / 1000 / 60;
                            if (time > 60) {
                                NLogUtil.w( NLogUtil.Warn_OPEN_TOO_LONG, "（1小时以上提醒）柜子已打开" + time + "分钟" );
                            }
                        }
                    } else {
                        openTime = 0;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
